﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace RonaldCamcam.XBeeApiFramework.Wrapper
{
    public interface IXBeeSerial
    {
        event SerialDataReceivedEventHandler XBeeReceivedData;
        bool IsPortOpen { get; }
        void Send(byte[] data);
        void Close();
    }

    public class XBeeSerial : IXBeeSerial
    {
        public event SerialDataReceivedEventHandler XBeeReceivedData;

        private SerialPort _port;

        public XBeeSerial(string comPort, int baudRate, Parity parity, int dataBits, StopBits stopBits, int readTimeOut, int writeTimeOut)
        {
            _port = new SerialPort(comPort, baudRate, parity, dataBits, stopBits);
            _port.ReadTimeout = readTimeOut;
            _port.WriteTimeout = writeTimeOut;
            _port.DataReceived += XBeeReceivedData;
            
            _port.Open();
        }

        public bool IsPortOpen
        {
            get
            {
                return _port.IsOpen;
            }
        }

        public void Send(byte[] data)
        {
            if (_port.IsOpen)
            {
                _port.Write(data, 0, data.Length);
            }
            else
            {
                throw new ApplicationException("Port is currently closed");
            }
        }

        public void Close()
        {
            _port.Dispose();
            _port.Close();
        }
    }
}
